package com.cherrish.demo.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author cherrish
 * @time 2019-02-25 13:27
 * @name ThreadsTest
 * @desc:
 */
public class ThreadsTest {
    public static void main(String[] args) {
//        sushu();
        ExecutorService tpool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            tpool.execute(new Sushu1());
        }

    }

    private static void sushu(){
        for(int i = 0; i < 100; i++){
            if(primeNumber(i)){
                System.out.println(i + " is a prime number");
            }
        }
    }

    static class Sushu implements Runnable{
        private static AtomicInteger num = new AtomicInteger(1);
        @Override
        public void run() {
            int num1 ;
            while ((num1 = num.getAndAdd(1)) <= 100){
                try {
                    if(primeNumber(num1)){
                        System.out.println(Thread.currentThread().getName() + "===> " + num1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Sushu1 implements Runnable{
        private static int num;

        public synchronized static int getNum() {
            return num;
        }

        public synchronized static void setNum() {
            Sushu1.num = Sushu1.num + 1;
        }

        @Override
        public void run() {
            int num1 ;
            while ((num1 = getNum()) <= 100){
                try {
                    if(primeNumber(num1)){
                        System.out.println(Thread.currentThread().getName() + "===> " + num1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                setNum();
            }
        }
    }
    static boolean primeNumber(int num) {
        if(num < 2){
//            throw new Exception(num + " is not a prime number");
            return false;
        }
        for(int i = 2; i <= Math.sqrt(num); i++){
            if(num % i == 0){
                return false;
            }
        }
        return true;
    }
}
